package org.jeecg.modules.business.transfer.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.modules.basic.material.entity.BasicMaterial;
import org.jeecg.modules.basic.material.mapper.BasicMaterialMapper;
import org.jeecg.modules.basic.plant.entity.WmsSapWarehouseMap;
import org.jeecg.modules.basic.plant.mapper.WmsSapWarehouseMapMapper;
import org.jeecg.modules.business.transfer.entity.PaperPurchase;
import org.jeecg.modules.business.transfer.entity.PaperPurchaseMaterial;
import org.jeecg.modules.business.transfer.entity.PaperWarning;
import org.jeecg.modules.business.transfer.entity.vo.PaperPurchaseParam;
import org.jeecg.modules.business.transfer.mapper.PaperPurchaseMapper;
import org.jeecg.modules.business.transfer.mapper.PaperPurchaseMaterialMapper;
import org.jeecg.modules.business.transfer.mapper.PaperWarningMapper;
import org.jeecg.modules.business.transfer.service.IPaperPurchaseMaterialService;
import org.jeecg.modules.business.transfer.service.IPaperPurchaseService;
import org.jeecg.modules.dock.entity.dto.request.PaperPurchaseRequestDTO;
import org.jeecg.modules.dock.entity.dto.response.PaperPurchaseResponseDTO;
import org.jeecg.modules.dock.service.SapDockingRepeaterService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Collection;

/**
 * @Description: 纸筒采购任务
 * @Author: jeecg-boot
 * @Date:   2023-11-14
 * @Version: V1.0
 */
@Service
@Slf4j
public class PaperPurchaseServiceImpl extends ServiceImpl<PaperPurchaseMapper, PaperPurchase> implements IPaperPurchaseService {

	@Autowired
	private PaperPurchaseMapper paperPurchaseMapper;
	@Autowired
	private PaperPurchaseMaterialMapper wmsPaperPurchaseMaterialMapper;
	@Autowired
	private PaperWarningMapper paperWarningMapper;

	@Autowired
	private IPaperPurchaseMaterialService paperPurchaseMaterialService;
	@Autowired
	private SapDockingRepeaterService sapDockingRepeaterService;
	@Autowired
	private BasicMaterialMapper basicMaterialMapper;
	@Autowired
	private WmsSapWarehouseMapMapper sapWarehouseMapMapper;
	
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String saveMain(PaperPurchase paperPurchase, List<PaperPurchaseMaterial> wmsPaperPurchaseMaterialList) {
		paperPurchaseMapper.insert(paperPurchase);
		if(wmsPaperPurchaseMaterialList!=null && wmsPaperPurchaseMaterialList.size()>0) {
			for(PaperPurchaseMaterial entity:wmsPaperPurchaseMaterialList) {
				//外键设置
				entity.setPaperPurchaseId(paperPurchase.getId());
				wmsPaperPurchaseMaterialMapper.insert(entity);
				// 更新纸筒库存预警数据状态为已处理
				if (StringUtils.isNotBlank(entity.getPaperWarningId())) {
					PaperWarning paperWarning = new PaperWarning();
					paperWarning.setId(entity.getPaperWarningId());
					paperWarning.setStatus("2");
					paperWarning.setPaperPurchaseTaskId(paperPurchase.getId());
					paperWarningMapper.updateById(paperWarning);
				}
			}
		}
		return paperPurchase.getId();
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void updateMain(PaperPurchase paperPurchase,List<PaperPurchaseMaterial> wmsPaperPurchaseMaterialList) {
		paperPurchaseMapper.updateById(paperPurchase);
		
		//1.先删除子表数据
		wmsPaperPurchaseMaterialMapper.deleteByMainId(paperPurchase.getId());
		
		//2.子表数据重新插入
		if(wmsPaperPurchaseMaterialList!=null && wmsPaperPurchaseMaterialList.size()>0) {
			for(PaperPurchaseMaterial entity:wmsPaperPurchaseMaterialList) {
				//外键设置
				entity.setPaperPurchaseId(paperPurchase.getId());
				wmsPaperPurchaseMaterialMapper.insert(entity);
			}
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delMain(String id) {
		// 更新纸筒库存预警数据状态为未处理
		List<PaperPurchaseMaterial> list = wmsPaperPurchaseMaterialMapper.selectByMainId(id);
		for (PaperPurchaseMaterial material : list) {
			if (StringUtils.isNotBlank(material.getPaperWarningId())) {
				paperWarningMapper.update(null, new LambdaUpdateWrapper<PaperWarning>()
						.eq(PaperWarning::getId, material.getPaperWarningId())
						.set(PaperWarning::getStatus, "1")
						.set(PaperWarning::getPaperPurchaseTaskId, null));
			}
		}
		wmsPaperPurchaseMaterialMapper.deleteByMainId(id);
		paperPurchaseMapper.deleteById(id);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void delBatchMain(Collection<? extends Serializable> idList) {
		for(Serializable id:idList) {
			wmsPaperPurchaseMaterialMapper.deleteByMainId(id.toString());
			paperPurchaseMapper.deleteById(id);
		}
	}

	@Override
	public void send(String id) {
		log.info("纸筒采购任务发送sap开始");
		List<PaperPurchaseRequestDTO> list = new ArrayList<>();
		List<PaperPurchaseMaterial> materials = paperPurchaseMaterialService.selectByMainId(id);
		String uuid = IdUtil.randomUUID();
		for (PaperPurchaseMaterial material : materials) {
			PaperPurchaseRequestDTO dto = new PaperPurchaseRequestDTO();
			BasicMaterial basicMaterial = basicMaterialMapper.selectById(material.getWmsBasicMaterialId());
			dto.setMaterial(basicMaterial.getCode());
			WmsSapWarehouseMap one = sapWarehouseMapMapper.selectOne(new LambdaQueryWrapper<WmsSapWarehouseMap>()
					.eq(WmsSapWarehouseMap::getWmsBasicWarehouseId, material.getWmsBasicWarehouseId())
					.last("limit 1"));
			dto.setFactory(one.getSapLocation());
			dto.setPurchaseQuantity(new BigDecimal(material.getPurchaseQuantity()));
			dto.setUuid(uuid);
			list.add(dto);
		}

		List<PaperPurchaseResponseDTO> responseDTOS = new ArrayList<>();
		try {
			responseDTOS = sapDockingRepeaterService.sapPushPaperPurchase(list);
		}catch (Exception e){
			throw new JeecgBootException("纸筒采购任务发送sap失败: " + e.getMessage());
		}
		log.info("纸筒采购任务发送sap结束 响应: {}", responseDTOS);
		if (CollectionUtil.isNotEmpty(responseDTOS)) {
			PaperPurchaseResponseDTO res = responseDTOS.get(0);
			if ("E".equals(res.getResult())) {
				throw new JeecgBootException("纸筒采购任务发送sap失败: " + res.getMessage());
			}
		}
		//将状态改为已发送
		PaperPurchase po = paperPurchaseMapper.selectById(id);
		po.setDocumentStatus("3");
		paperPurchaseMapper.updateById(po);
		log.info("纸筒采购任务发送sap结束");
	}

	/**
	 * 分页
	 * @param page
	 * @param param
	 * @return
	 */
	@Override
	public Page<PaperPurchase> listByPage(Page<PaperPurchase> page, PaperPurchaseParam param) {
		List<PaperPurchase> list = paperPurchaseMapper.listByPage(page, param);
		return page.setRecords(list);
	}

}
